const inputPath = process.argv[2] // 获取输入的文件路径

const path = require('path')
const fs = require('fs')
const axios = require('axios')

const mdPath = path.resolve(inputPath) // md文件绝对路径，如：/Users/xxx/Desktop/test.md
let rootPath = '' // md文件所在目录

// 在md文件所在目录创建images文件夹，保存本地图片
try {
    const { dir } = path.parse(mdPath)
    rootPath = dir
    fs.mkdirSync(`${rootPath}/images`)
} catch (err) {
    console.log(err.code)
}

main()

// 主函数
async function main() {
    let content = fs.readFileSync(mdPath, 'utf8')
    const imgList = getImgsByPath(mdPath)
    for (const img of imgList) {
        const { imageName } = await getLocalImgPath(img)
        content = content.replace(img, `./images/${imageName}`)
        fs.writeFileSync(mdPath, content)
    }
}

// 根据文件路径获取所有图片链接
function getImgsByPath(filePath) {
    let content = fs.readFileSync(filePath, 'utf8')
    const pattern = /!\[(.*?)\]\((.*?)\)/gm // 匹配图片正则
    const imgList = content.match(pattern) || [] // ![img](http://hello.com/image.png)
    return imgList.map((item) => {
        return item.split('](')[1].slice(0, -1) // http://hello.com/image.png
    })
}

// 获取本地图片路径，下载图片并保存在images目录
function getLocalImgPath(imgUrl) {
    const fileType = imgUrl.split('.').slice(-1)[0] // 获取图片格式
    const imageName = `${new Date().getTime()}${fileType ? `.${fileType}` : ''}`
    return axios({
        url: imgUrl,
        responseType: 'stream',
        timeout: 10000,
    }).then((response) => {
        return new Promise((resolve, reject) => {
            const imagePath = `${rootPath}/images/${imageName}`
            response.data
                .pipe(fs.createWriteStream(imagePath))
                .on('finish', () => resolve({ imageName, imagePath }))
                .on('error', (e) => reject(e))
        })
    })
}
